// import { useEffect, useState } from 'react'; , RealnameFilled, PhoneOutlined
import { Form, Input, Checkbox, Button, omit, Toast, stopPropagation, SigninFilled, LockFilled, VerificationFilled, getRandomNumber, RealnameFilled } from 'esy-ui';
import { useEffect, useState } from 'react';
import { useFormatText, useNavigation } from '@/hooks';
import { postRegistry } from '@/services';
import { REG_ACCOUNT, REG_PSW } from '@/constants';
import { useUserInfoStore } from '@/mobx';
import { ssGetItem, ssSetItem } from '@/utils';

const FormItem = Form.Item;

function Title({ title }: any) {
  return (
    <div className='flex items-center text-xl mb-3 text-white gap-1'>
      <div className='w-1 h-6 bg-primary rounded' />
      <div>{title}</div>
    </div>
  );
}

const items = [
  {
    name: 'account',
    placeholder: 'please_account_4_12',
    prefix: <SigninFilled className='text-lg mr-1' />,
    maxlength: 12,
    required: true,
    suffix: null,
  },
  {
    name: 'password',
    placeholder: 'please_password_6_12',
    maxlength: 12,
    prefix: <LockFilled className='text-lg mr-1' />,
    type: 'password',
    required: true,
    suffix: null,
  },
  {
    name: 'repassword',
    placeholder: 'please_repassword_6_12',
    prefix: <LockFilled className='text-lg mr-1' />,
    maxlength: 12,
    type: 'password',
    required: true,
    suffix: null,
  },
  {
    name: 'realname-title',
  },
  {
    name: 'RealName',
    placeholder: 'please_realname',
    prefix: <RealnameFilled className='text-lg mr-1' />,
    maxlength: 30,
    required: true,
  },
  // {
  //   name: 'phone',
  //   placeholder: 'please_phone',
  //   prefix: <PhoneOutlined className='text-lg mr-1' />,
  //   maxlength: 11,
  //   required: true,
  // },
  {
    name: 'verifyCode',
    type: 'number',
    placeholder: 'please_code',
    prefix: <VerificationFilled className='text-lg mr-1' />,
    maxlength: 6,
    required: true,
    suffix: (code, changeCode) => (
      <div className='text-primary text-lg cursor-pointer' onClick={changeCode}>
        {code}
      </div>
    ),
  },
];

function Register() {
  const [form] = Form.useForm();
  const { text } = useFormatText();
  const navigation = useNavigation();
  const [vcode, setVcode] = useState(null);
  const { changeUserInfo } = useUserInfoStore();

  const changeCode = () => {
    setVcode(getRandomNumber(6));
  };

  useEffect(() => {
    changeCode();
  }, []);

  const onSubmit = () => {
    if (form) {
      form
        .validate()
        .then((values) => {
          postRegistry({ ...omit(values, ['repassword', 'read']), spreadID: ssGetItem('ivt_code') || '0' })
            .then((res: any) => {
              // 绑定后清除
              ssSetItem('ivt_code', '');
              changeUserInfo(res.Data);
              // 登录成功的操作
              navigation('/');
            })
            .catch(() => {
              // 登录失败的操作
              changeCode();
            });
        })
        .catch((err) => {
          Toast.show({ content: `${err?.errorFields[0].message}` });
          changeCode();
        });
    }
  };

  // 表单校验
  const rulesObj = {
    account: [
      {
        validator: (_, value) => {
          if (!value || !REG_ACCOUNT.test(value)) {
            return new Error(text('please_account_4_12'));
          }
          return Promise.resolve();
        },
      },
    ],
    password: [
      {
        validator: (_, value) => {
          if (!value || !REG_PSW.test(value)) {
            return new Error(text('please_password_6_12'));
          }
          const repassword = form.getFieldValue('repassword');
          if (value && repassword && value !== repassword) {
            return new Error(text('twice_password_diff'));
          }
          return Promise.resolve();
        },
      },
    ],
    repassword: [
      {
        validator: (_, value) => {
          if (!value || !REG_PSW.test(value)) {
            return new Error(text('please_password_6_12'));
          }
          const password = form.getFieldValue('password');
          if (value && password && value !== password) {
            return new Error(text('twice_password_diff'));
          }
          return Promise.resolve();
        },
      },
    ],
    RealName: [
      {
        validator: (_, value) => {
          if (!value) {
            return new Error(text('please_realname'));
          }
          return Promise.resolve();
        },
      },
    ],
    verifyCode: [
      {
        validator: (_, value) => {
          if (!value) {
            return new Error(`${text('please_code')}`);
          }
          if (value !== vcode) {
            return new Error(`${text('code_fail')}`);
          }
          return Promise.resolve();
        },
      },
    ],
  };

  return (
    <Form form={form}>
      <Title title={text('register_account')} />
      {items.map((it) => {
        if (it.name === 'realname-title') {
          return <Title title={text('text_209')} />;
        }
        return (
          <div className='relative' key={it.name}>
            {it.required ? <span className='absolute -left-2 top-0 text-primary z-1'>*</span> : null}
            <FormItem name={it.name} rules={rulesObj[it.name]}>
              <Input
                prefix={it.prefix}
                placeholder={text(it.placeholder)}
                type={(it.type || 'text') as any}
                maxLength={it.maxlength}
                suffix={typeof it.suffix === 'function' ? it.suffix(vcode, changeCode) : it.suffix}
              />
            </FormItem>
          </div>
        );
      })}

      <FormItem
        name='read'
        initialValue
        label={
          <div className='text-sm text-split flex-1'>
            {text('text_9')}
            <span
              className='text-primary underline'
              onClick={(e) => {
                stopPropagation(e);
                navigation('/');
              }}
            >
              {text('text_10')}
            </span>
          </div>
        }
      >
        <Checkbox classNames={{ box: 'flex', label: 'ml-2 flex-1' }} />
      </FormItem>
      <Button className='w-full rounded' type='primary' onClick={onSubmit}>
        {text('register')}
      </Button>
    </Form>
  );
}

export default Register;
